{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WZ1G8QHhdHZR"
   },
   "source": [
    "##### Copyright 2020 The Cirq Developers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "cellView": "form",
    "id": "KQa9t_gadIuR"
   },
   "outputs": [],
   "source": [
    "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "# https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "xwec7FrkdFmi"
   },
   "source": [
    "# Custom gates"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "5KZia7jmdJ3V"
   },
   "source": [
    "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://www.example.org/cirq/custom_gates\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on QuantumLib</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/custom_gates.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/master/docs/custom_gates.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/custom_gates.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
    "  </td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "id": "bd9529db1c0b"
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    import cirq\n",
    "except ImportError:\n",
    "    print(\"installing cirq...\")\n",
    "    !pip install --quiet cirq\n",
    "    print(\"installed cirq.\")\n",
    "    import cirq\n",
    "    \n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "y8P1T6duC-yo"
   },
   "source": [
    "Standard gates such as Pauli gates and `CNOT`s are defined in `cirq.ops` as described [here](gates.ipynb). To use a unitary which is not a standard gate in a circuit, one can create a custom gate as described in this guide."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "71ae01d45738"
   },
   "source": [
    "## General pattern"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ce675022b0b4"
   },
   "source": [
    "Gates are classes in Cirq. To define custom gates, we inherit from a base gate class and define a few methods.\n",
    "\n",
    "There are two general patterns:\n",
    "\n",
    "1. Inherit from `cirq.Gate`.\n",
    "  - Define one of the `_num_qubits_` or `_qid_shape_` methods.\n",
    "  - Define one of the `_unitary_` or `_decompose_` methods.\n",
    "  \n",
    "2. Inherit from `cirq.SingleQubitGate`, `cirq.TwoQubitGate`, or `cirq.ThreeQubitGate`.\n",
    "  - Define one of the `_unitary_` or `_decompose_` methods.\n",
    "\n",
    "> *Note*: Methods beginning and ending with one or more underscores are *magic methods* and are used by Cirq's protocols or built-in Python functions. More information about magic methods is included at the end of this guide.\n",
    "\n",
    "We demonstrate these patterns via the following examples.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "38c6a07df259"
   },
   "source": [
    "## From a unitary"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "58228b4b49f4"
   },
   "source": [
    "One can create a custom Cirq gate from a unitary matrix in the following manner. Here, we define a gate which corresponds to the unitary\n",
    "\n",
    "\n",
    "$$ U = \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 & 1 \\\\ -1 & 1 \\end{matrix} \\right] . $$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "id": "66346efdd520"
   },
   "outputs": [],
   "source": [
    "\"\"\"Define a custom single-qubit gate.\"\"\"\n",
    "class MyGate(cirq.Gate):\n",
    "    def __init__(self):\n",
    "        super(MyGate, self)\n",
    "        \n",
    "    def _num_qubits_(self):\n",
    "        return 1\n",
    "    \n",
    "    def _unitary_(self):\n",
    "        return np.array([\n",
    "            [1.0,  1.0],\n",
    "            [-1.0, 1.0]\n",
    "        ]) / np.sqrt(2)\n",
    "    \n",
    "    def _circuit_diagram_info_(self, args):\n",
    "        return \"G\"\n",
    "\n",
    "my_gate = MyGate()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "873c956ccf0e"
   },
   "source": [
    "In this example, the `_num_qubits_` method tells Cirq that this gate acts on a single-qubit, and the `_unitary_` method defines the unitary of the gate. The `_circuit_diagram_info_` method tells Cirq how to display the gate in a circuit, as we will see below.\n",
    "\n",
    "Once this gate is defined, it can be used like any standard gate in Cirq."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "id": "ec8550e51178"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Circuit with custom gates:\n",
      "0: ───G───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Use the custom gate in a circuit.\"\"\"\n",
    "circ = cirq.Circuit(\n",
    "    my_gate.on(cirq.LineQubit(0))\n",
    ")\n",
    "\n",
    "print(\"Circuit with custom gates:\")\n",
    "print(circ)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "dc0e4ee48211"
   },
   "source": [
    "When we print the circuit, we see the symbol we specified in the `_circuit_diagram_info_` method.\n",
    "\n",
    "Circuits with custom gates can be simulated in the same manner as circuits with standard gates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "id": "3885c629a1ef"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "measurements: (no measurements)\n",
      "output vector: 0.707|0⟩ - 0.707|1⟩\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Simulate a circuit with a custom gate.\"\"\"\n",
    "sim = cirq.Simulator()\n",
    "\n",
    "res = sim.simulate(circ)\n",
    "print(res)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "874bdef876ed"
   },
   "source": [
    "An alternative to inheriting from `cirq.Gate` is to inherit from `cirq.SingleQubitGate`, in which case defining `_num_qubits_` is unnecessary. There is also `cirq.TwoQubitGate` and `cirq.ThreeQubitGate` for two-qubit and three-qubit gates, respectively. An example of a defining a two-qubit gate is shown below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "id": "71dd8d4666fc"
   },
   "outputs": [],
   "source": [
    "\"\"\"Define a custom two-qubit gate.\"\"\"\n",
    "class AnotherGate(cirq.TwoQubitGate):\n",
    "    def __init__(self):\n",
    "        super(AnotherGate, self)\n",
    "    \n",
    "    def _unitary_(self):\n",
    "        return np.array([\n",
    "            [1.0, -1.0, 0.0,  0.0],\n",
    "            [0.0,  0.0, 1.0,  1.0],\n",
    "            [1.0,  1.0, 0.0,  0.0],\n",
    "            [0.0,  0.0, 1.0, -1.0]\n",
    "        ]) / np.sqrt(2)\n",
    "    \n",
    "    def _circuit_diagram_info_(self, args):\n",
    "        return \"Top wire symbol\", \"Bottom wire symbol\"\n",
    "\n",
    "this_gate = AnotherGate()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9c79b54f0ab4"
   },
   "source": [
    "Here, the `_circuit_diagram_info_` method returns two symbols (one for each wire) since it is a two-qubit gate."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "id": "280e34a34bd6"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Circuit with custom two-qubit gate:\n",
      "0: ───Top wire symbol──────\n",
      "      │\n",
      "1: ───Bottom wire symbol───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Use the custom two-qubit gate in a circuit.\"\"\"\n",
    "circ = cirq.Circuit(\n",
    "    this_gate.on(*cirq.LineQubit.range(2))\n",
    ")\n",
    "\n",
    "print(\"Circuit with custom two-qubit gate:\")\n",
    "print(circ)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "45a8342180aa"
   },
   "source": [
    "As above, this circuit can also be simulated in the expected way."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "c896c2bb5f23"
   },
   "source": [
    "### With parameters"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ef59ca39c94c"
   },
   "source": [
    "Custom gates can be defined and used with parameters. For example, to define the gate\n",
    "\n",
    "$$ R(\\theta) = \\left[ \\begin{matrix} \\cos \\theta & \\sin \\theta \\\\ \\sin \\theta & - \\cos \\theta \\end{matrix} \\right], $$\n",
    "\n",
    "we can do the following."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "id": "262d28526fef"
   },
   "outputs": [],
   "source": [
    "\"\"\"Define a custom gate with a parameter.\"\"\"\n",
    "class RotationGate(cirq.Gate):\n",
    "    def __init__(self, theta):\n",
    "        super(RotationGate, self)\n",
    "        self.theta = theta\n",
    "        \n",
    "    def _num_qubits_(self):\n",
    "        return 1\n",
    "    \n",
    "    def _unitary_(self):\n",
    "        return np.array([\n",
    "            [np.cos(self.theta), np.sin(self.theta)],\n",
    "            [np.sin(self.theta), -np.cos(self.theta)]\n",
    "        ]) / np.sqrt(2)\n",
    "    \n",
    "    def _circuit_diagram_info_(self, args):\n",
    "        return f\"R({self.theta})\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "8a10fdb09fca"
   },
   "source": [
    "This gate can be used in a circuit as shown below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "id": "485c560f0d25"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Circuit with a custom rotation gate:\n",
      "0: ───R(0.1)───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Use the custom gate in a circuit.\"\"\"\n",
    "circ = cirq.Circuit(\n",
    "    RotationGate(theta=0.1).on(cirq.LineQubit(0))\n",
    ")\n",
    "\n",
    "print(\"Circuit with a custom rotation gate:\")\n",
    "print(circ)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "baf273b2fe60"
   },
   "source": [
    "## From a known decomposition"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "708300eb2c33"
   },
   "source": [
    "Custom gates can also be defined from a known decomposition (of gates). This is useful, for example, when groups of gates appear repeatedly in a circuit, or when a standard decomposition of a gate into primitive gates is known.\n",
    "\n",
    "We show an example below of a custom swap gate defined from a known decomposition of three CNOT gates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "id": "2c656362cd95"
   },
   "outputs": [],
   "source": [
    "class MySwap(cirq.TwoQubitGate):\n",
    "    def __init__(self):\n",
    "        super(MySwap, self)\n",
    "    \n",
    "    def _decompose_(self, qubits):\n",
    "        a, b = qubits\n",
    "        yield cirq.CNOT(a, b)\n",
    "        yield cirq.CNOT(b, a)\n",
    "        yield cirq.CNOT(a, b)\n",
    "    \n",
    "    def _circuit_diagram_info_(self, args):\n",
    "        return [\"CustomSWAP\"] * self.num_qubits()\n",
    "\n",
    "my_swap = MySwap()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "829c4602757a"
   },
   "source": [
    "The `_decompose_` method yields the operations which implement the custom gate. (One can also return a list of operations instead of a generator.)\n",
    "\n",
    "When we use this gate in a circuit, the individual gates in the decomposition do not appear in the circuit. Instead, the `_circuit_diagram_info_` appears in the circuit. As mentioned, this can be useful for interpreting circuits at a higher level than individual (primitive) gates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "id": "psYGZcjUEF5V"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Circuit:\n",
      "0: ───X───CustomSWAP───\n",
      "          │\n",
      "1: ───────CustomSWAP───\n"
     ]
    }
   ],
   "source": [
    "\"\"\"Use the custom gate in a circuit.\"\"\"\n",
    "qreg = cirq.LineQubit.range(2)\n",
    "circ = cirq.Circuit(\n",
    "    cirq.X(qreg[0]),\n",
    "    my_swap.on(*qreg)\n",
    ")\n",
    "\n",
    "print(\"Circuit:\")\n",
    "print(circ)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "856b1cdf0117"
   },
   "source": [
    "We can simulate this circuit and verify it indeed swaps the qubits."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "id": "0cafcf4c4197"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "measurements: (no measurements)\n",
       "output vector: |01⟩"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"\"\"Simulate the circuit.\"\"\"\n",
    "sim.simulate(circ)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "09f425a61484"
   },
   "source": [
    "## More on magic methods and protocols"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "d63f32eb1ac7"
   },
   "source": [
    "As mentioned, methods such as `_unitary_` which we have seen are known as \"magic\n",
    "methods.\" Much of cirq relies on \"magic methods\", which are methods prefixed with one or\n",
    "two underscores and used by cirq's protocols or built-in python methods.\n",
    "For instance,  python translates `cirq.Z**0.25` into\n",
    "`cirq.Z.__pow__(0.25)`.  Other uses are specific to cirq and are found in the\n",
    "protocols subdirectory.  They are defined below.\n",
    "\n",
    "At minimum, you will need to define either the ``_num_qubits_`` or\n",
    "``_qid_shape_`` magic method to define the number of qubits (or qudits) used\n",
    "in the gate.  For convenience one can use the ``SingleQubitGate``,\n",
    "``TwoQubitGate``, and ``ThreeQubitGate`` classes for these common gate sizes."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "d05fa2e8d1ab"
   },
   "source": [
    "### Standard python magic methods\n",
    "\n",
    "There are many standard magic methods in python.  Here are a few of the most\n",
    "important ones used in cirq:\n",
    "  * `__str__` for user-friendly string output and  `__repr__` is the python-friendly string output, meaning that `eval(repr(y))==y` should always be true.\n",
    "  * `__eq__` and `__hash__` which define whether objects are equal or not.  You\n",
    "  can also use `cirq.value.value_equality` for objects that have a small list\n",
    "  of sub-values that can be compared for equality.\n",
    "  * Arithmetic functions such as `__pow__`, `__mul__`, `__add__` define the\n",
    "  action of `**`, `*`, and `+` respectively.\n",
    "   \n",
    "### `cirq.num_qubits` and `def _num_qubits_`\n",
    "\n",
    "A `Gate` must implement the `_num_qubits_` (or `_qid_shape_`) method.\n",
    "This method returns an integer and is used by `cirq.num_qubits` to determine\n",
    "how many qubits this gate operates on.\n",
    "\n",
    "### `cirq.qid_shape` and `def _qid_shape_`\n",
    "\n",
    "A qudit gate or operation must implement the `_qid_shape_` method that returns a\n",
    "tuple of integers.  This method is used to determine how many qudits the gate or\n",
    "operation operates on and what dimension each qudit must be.  If only the\n",
    "`_num_qubits_` method is implemented, the object is assumed to operate only on\n",
    "qubits. Callers can query the qid shape of the object by calling\n",
    "`cirq.qid_shape` on it. See [qudit documentation](qudits.ipynb) for more\n",
    "information.\n",
    "\n",
    "### `cirq.unitary` and `def _unitary_`\n",
    "\n",
    "When an object can be described by a unitary matrix, it can expose that unitary\n",
    "matrix by implementing a `_unitary_(self) -> np.ndarray` method.\n",
    "Callers can query whether or not an object has a unitary matrix by calling\n",
    "`cirq.unitary` on it.\n",
    "The `_unitary_` method may also return `NotImplemented`, in which case\n",
    "`cirq.unitary` behaves as if the method is not implemented.\n",
    "\n",
    "### `cirq.decompose` and `def _decompose_`\n",
    "\n",
    "Operations and gates can be defined in terms of other operations by implementing\n",
    "a `_decompose_` method that returns those other operations. Operations implement\n",
    "`_decompose_(self)` whereas gates implement `_decompose_(self, qubits)`\n",
    "(since gates don't know their qubits ahead of time).\n",
    "\n",
    "The main requirements on the output of `_decompose_` methods are:\n",
    "\n",
    "1. DO NOT CREATE CYCLES. The `cirq.decompose` method will iterative decompose until it finds values satisfying a `keep` predicate. Cycles cause it to enter an infinite loop.\n",
    "2. Head towards operations defined by Cirq, because these operations have good decomposition methods that terminate in single-qubit and two qubit gates.\n",
    "These gates can be understood by the simulator, optimizers, and other code.\n",
    "3. All that matters is functional equivalence.\n",
    "Don't worry about staying within or reaching a particular gate set; it's too hard to predict what the caller will want. Gate-set-aware decomposition is useful, but *this is not the protocol that does that*.\n",
    "Gate-set-aware decomposition may be added in the future, but doesn't exist within Cirq at the moment.\n",
    "\n",
    "For example, `cirq.CCZ` decomposes into a series of `cirq.CNOT` and `cirq.T` operations.\n",
    "This allows code that doesn't understand three-qubit operation to work with `cirq.CCZ`; by decomposing it into operations they do understand.\n",
    "As another example, `cirq.TOFFOLI` decomposes into a `cirq.H` followed by a `cirq.CCZ` followed by a `cirq.H`.\n",
    "Although the output contains a three qubit operation (the CCZ), that operation can be decomposed into two qubit and one qubit operations.\n",
    "So code that doesn't understand three qubit operations can deal with Toffolis by decomposing them, and then decomposing the CCZs that result from the initial decomposition.\n",
    "\n",
    "In general, decomposition-aware code consuming operations is expected to recursively decompose unknown operations until the code either hits operations it understands or hits a dead end where no more decomposition is possible.\n",
    "The `cirq.decompose` method implements logic for performing exactly this kind of recursive decomposition.\n",
    "Callers specify a `keep` predicate, and optionally specify intercepting and fallback decomposers, and then `cirq.decompose` will repeatedly decompose whatever operations it was given until the operations satisfy the given `keep`.\n",
    "If `cirq.decompose` hits a dead end, it raises an error.\n",
    "\n",
    "Cirq doesn't make any guarantees about the \"target gate set\" decomposition is heading towards.\n",
    "`cirq.decompose` is not a method\n",
    "Decompositions within Cirq happen to converge towards X, Y, Z, CZ, PhasedX, specified-matrix gates, and others.\n",
    "But this set will vary from release to release, and so it is important for consumers of decompositions to look for generic properties of gates,\n",
    "such as \"two qubit gate with a unitary matrix\", instead of specific gate types such as CZ gates.\n",
    "\n",
    "### `cirq.inverse` and `__pow__`\n",
    "\n",
    "Gates and operations are considered to be *invertible* when they implement a `__pow__` method that returns a result besides `NotImplemented` for an exponent of -1.\n",
    "This inverse can be accessed either directly as `value**-1`, or via the utility method `cirq.inverse(value)`.\n",
    "If you are sure that `value` has an inverse, saying `value**-1` is more convenient than saying `cirq.inverse(value)`.\n",
    "`cirq.inverse` is for cases where you aren't sure if `value` is invertible, or where `value` might be a *sequence* of invertible operations.\n",
    "\n",
    "`cirq.inverse` has a `default` parameter used as a fallback when `value` isn't invertible.\n",
    "For example, `cirq.inverse(value, default=None)` returns the inverse of `value`, or else returns `None` if `value` isn't invertible.\n",
    "(If no `default` is specified and `value` isn't invertible, a `TypeError` is raised.)\n",
    "\n",
    "When you give `cirq.inverse` a list, or any other kind of iterable thing, it will return a sequence of operations that (if run in order) undoes the operations of the original sequence (if run in order).\n",
    "Basically, the items of the list are individually inverted and returned in reverse order.\n",
    "For example, the expression `cirq.inverse([cirq.S(b), cirq.CNOT(a, b)])` will return the tuple `(cirq.CNOT(a, b), cirq.S(b)**-1)`.\n",
    "\n",
    "Gates and operations can also return values beside `NotImplemented` from their `__pow__` method for exponents besides `-1`.\n",
    "This pattern is used often by Cirq.\n",
    "For example, the square root of X gate can be created by raising `cirq.X` to 0.5:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "id": "a37d151e71ed"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.+0.j 1.+0.j]\n",
      " [1.+0.j 0.+0.j]]\n",
      "[[0.5+0.5j 0.5-0.5j]\n",
      " [0.5-0.5j 0.5+0.5j]]\n"
     ]
    }
   ],
   "source": [
    "print(cirq.unitary(cirq.X))\n",
    "# prints\n",
    "# [[0.+0.j 1.+0.j]\n",
    "#  [1.+0.j 0.+0.j]]\n",
    "\n",
    "sqrt_x = cirq.X**0.5\n",
    "print(cirq.unitary(sqrt_x))\n",
    "# prints\n",
    "# [[0.5+0.5j 0.5-0.5j]\n",
    "#  [0.5-0.5j 0.5+0.5j]]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "6fe65e2eb967"
   },
   "source": [
    "The Pauli gates included in Cirq use the convention ``Z**0.5 ≡ S ≡ np.diag(1, i)``, ``Z**-0.5 ≡ S**-1``, ``X**0.5 ≡ H·S·H``, and the square root of ``Y`` is inferred via the right hand rule.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "9d8cecee52e8"
   },
   "source": [
    "### `_circuit_diagram_info_(self, args)` and `cirq.circuit_diagram_info(val, [args], [default])`\n",
    "\n",
    "Circuit diagrams are useful for visualizing the structure of a `Circuit`.\n",
    "Gates can specify compact representations to use in diagrams by implementing a `_circuit_diagram_info_` method.\n",
    "For example, this is why SWAP gates are shown as linked '×' characters in diagrams.\n",
    "\n",
    "The `_circuit_diagram_info_` method takes an `args` parameter of type `cirq.CircuitDiagramInfoArgs` and returns either\n",
    "a string (typically the gate's name), a sequence of strings (a label to use on each qubit targeted by the gate), or an\n",
    "instance of `cirq.CircuitDiagramInfo` (which can specify more advanced properties such as exponents and will expand\n",
    "in the future).\n",
    "\n",
    "You can query the circuit diagram info of a value by passing it into `cirq.circuit_diagram_info`."
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [
    "Sh9QBnKbFf_B"
   ],
   "name": "custom_gates.ipynb",
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
